package com.xyd.auth.service.impl;

import com.xyd.auth.service.ISysMenuService;
import com.xyd.auth.service.ISysUserService;
import com.xyd.model.system.SysUser;
import com.xyd.auth.security.custom.CustomUser;
import com.xyd.auth.security.custom.CustomUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 登录认证业务
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements CustomUserDetailService {
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    ISysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("进入到CustomUserDetailServiceImpl的实现类访问数据库");
        SysUser sysUser = sysUserService.getByUsername(username);
        if(sysUser == null){
            throw new UsernameNotFoundException("用户名不存在");
        }else if(sysUser.getStatus() == 0){
            throw  new RuntimeException("该用户被禁用");
        }
        // 根据用户ID得到用户可以操作的按钮权限数据
        List<String> sysUserPermsByUserId = sysMenuService.findSysUserPermsByUserId(sysUser.getId());
        log.info("service当前用户权限Perms：{}",sysUserPermsByUserId);
        // 不能直接封装 创建一个新的集合
        List<SimpleGrantedAuthority> simpleGrantedAuthorityArrayList = new ArrayList<SimpleGrantedAuthority>();
        // 把查询出来的数据放进这个SimpleGrantedAuthority的集合
        for(String sysUserPerms : sysUserPermsByUserId){
            simpleGrantedAuthorityArrayList.add(new SimpleGrantedAuthority(sysUserPerms));
        }

        log.info("封装之后满足security的权限对象：{}",simpleGrantedAuthorityArrayList);
        return new CustomUser(sysUser, simpleGrantedAuthorityArrayList);
    }
}
